import { defineEventHandler, getCookie, readBody, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';

export default defineEventHandler(async (event) => {
  try {
    const userId = getCookie(event, 'userId');
    if (!userId) {
      throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
    }

    const { noteId, keepCount = 10 } = await readBody(event);
    if (!noteId) {
      throw createError({ statusCode: 400, statusMessage: 'Note ID is required' });
    }

    const db = await getDbConnection();
    
    // 验证笔记是否属于当前用户
    const note = await db.get(
      'SELECT id FROM notes WHERE id = ? AND user_id = ?',
      [noteId, userId]
    );
    
    if (!note) {
      throw createError({ statusCode: 404, statusMessage: 'Note not found' });
    }
    
    // 获取要保留的版本ID（最新的keepCount个版本）
    const versionsToKeep = await db.all(
      `SELECT id FROM note_versions 
       WHERE note_id = ? 
       ORDER BY version_number DESC 
       LIMIT ?`,
      [noteId, keepCount]
    );
    
    const keepIds = versionsToKeep.map(v => v.id);
    
    if (keepIds.length === 0) {
      return { success: true, deletedCount: 0 };
    }
    
    // 删除不在保留列表中的版本
    const result = await db.run(
      `DELETE FROM note_versions 
       WHERE note_id = ? AND id NOT IN (${keepIds.map(() => '?').join(',')})`,
      [noteId, ...keepIds]
    );
    
    return { 
      success: true, 
      deletedCount: result.changes || 0,
      keptCount: keepIds.length
    };
  } catch (error) {
    console.error('Error cleaning up versions:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to cleanup versions' });
  }
});
